package com.example.membersteward.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.membersteward.common.CommonResult;
import com.example.membersteward.entity.RoleUser;
import com.example.membersteward.entity.User;
import com.example.membersteward.entity.vo.UserVo;
import com.example.membersteward.enums.UserStatus;
import com.example.membersteward.exception.ServiceException;
import com.example.membersteward.mapper.RoleUserMapper;
import com.example.membersteward.service.RoleUserService;
import com.example.membersteward.service.UserService;
import com.example.membersteward.mapper.UserMapper;
import com.example.membersteward.util.BaseUtils;
import com.example.membersteward.util.JwtUtils;
import com.example.membersteward.util.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author 26690
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-04-08 22:52:37
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    AuthenticationManager authenticationManager;
    @Resource
    UserDetailsServiceImpl userDetailsService;
    @Resource
    JwtUtils jwtUtils;

    @Value("${user.username.regex}")
    private String usernameRegex;
    @Value("${user.password.regex}")
    private String passwordRegex;

    @Value("${user.username.regex-detail}")
    private String usernameRegexDetail;
    @Value("${user.password.regex-detail}")
    private String passwordRegexDetail;

    @Value("${resource.imgPath}")
    public String IMG_PATH;
    @Resource
    UserMapper userMapper;
    @Value("${resource.virtualPath}")
    private String VIRTUAL_PATH;
    @Value("${resource.defaultImg}")
    private String DEFAULT_IMG;
    @Resource
    RoleUserMapper roleUserMapper;

    @Override
    public CommonResult login(User user) {
        // 输入判断，为空判断
        CommonResult commonResult;
        CommonResult loginInfoCheckResult = loginInfoCheck(user);
        if (loginInfoCheckResult.isError()) {
            logger.error("输入信息有误: " + loginInfoCheckResult.get(CommonResult.MSG_TAG));
            return loginInfoCheckResult;
        }
        try {
            // 会调用userDetailsService.loadUserByUsername(user.getUserAcct())查询用户信息
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUserAcct(), user.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            User userDetails = (User) authentication.getPrincipal();
            System.out.println(userDetails.getUsername().hashCode());
            String jwt = jwtUtils.generateJwtToken(
                    userDetails.getUserId() // 实际应从User对象获取userId，此处简化示例（见下方注意）
            );
            System.out.println(jwtUtils.getUserIdFromJwtToken(jwt));
            commonResult = new CommonResult(200, "登录成功！");
            commonResult.put("token", jwt);
        } catch (Exception e) {
            commonResult = CommonResult.error();
            logger.error("操作异常！", e);
        }

        return commonResult;
    }

    private CommonResult loginInfoCheck(User user) {
        if (BaseUtils.isNull(user)) {
            return CommonResult.error("请输入登录信息！");
        }
        if (BaseUtils.isEmpty(user.getUserAcct()) || BaseUtils.isEmpty(user.getPassword())) {
            return CommonResult.error("请输入用户账户信息！");
        }
//        if (user.getPassword().length() < UserConstants.PASSWORD_MIN_LENGTH
//                || user.getPassword().length() > UserConstants.PASSWORD_MAX_LENGTH) {
//            return CommonResult.error("密码长度应在" + UserConstants.PASSWORD_MIN_LENGTH + "~" + UserConstants.PASSWORD_MAX_LENGTH + "内")
//        }
//        if (user.getUserAcct().length() < UserConstants.USERNAME_MIN_LENGTH
//                || user.getUserAcct().length() > UserConstants.USERNAME_MAX_LENGTH) {
//            return CommonResult.error("账号长度应在" + UserConstants.USERNAME_MIN_LENGTH + "~" + UserConstants.USERNAME_MAX_LENGTH + "内")
//        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public CommonResult register(UserVo user) {
        try {
            if (BaseUtils.isEmpty(user.getPassword())) {
                user.setPassword("123456a");
            }
            CommonResult checkResult = registerInfoCheck(user);
            if (checkResult.isError()) {
                return checkResult;
            }
//            user.setUserId(sequenceGenerator.generateSequence());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));  // 密码加密
            user.setCreateTime(new Date());
            user.setLastUpdateTime(new Date());
            user.setImgPath(VIRTUAL_PATH + DEFAULT_IMG);
            int ret = userMapper.insert(user);
            if (ret <= 0) {
                return CommonResult.error("新增用户失败");
            }


            if (BaseUtils.isNotEmpty(user.getRoleIds())) {
                List<String> roleIds = user.getRoleIds();
                int i = roleUserMapper.insertByAcct(roleIds, user.getUserAcct());
                if (i <= 0) {
                    return CommonResult.error("新增用户失败");
                }
            }
            return CommonResult.success("注册成功！");
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new ServiceException("执行异常");
        }
    }

    @Override
    public CommonResult getUserByPage(int pageNum, int pageSize, UserVo user) {
        try {
            Date startDate = null;
            Date endDate = null;
            int offset = (pageNum - 1) * pageSize;
            if (BaseUtils.isNotNull(user)) {
                if (BaseUtils.isNotNull(user.getStartDate())) {
                    startDate = BaseUtils.getMinDate(user.getStartDate());
                }
                if (BaseUtils.isNotNull(user.getEndDate())) {
                    endDate = BaseUtils.getMaxDate(user.getEndDate());
                }
            }
            IPage<UserVo> userPage = new Page<>();
            userPage.setRecords(userMapper.selectByPage(user, startDate, endDate, offset, pageSize));
            userPage.setTotal(userMapper.getTotalCount(user, startDate, endDate));
            return CommonResult.success(userPage);
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new ServiceException("执行异常");
        }
    }

    @Override
    public CommonResult resetPassword(User user) {
        try {
            if (BaseUtils.isNull(user) || BaseUtils.isNull(user.getUserId()) || user.getUserId() <= 0
                    || BaseUtils.isEmpty(user.getPassword())) {
                return CommonResult.error("输入信息有误");
            }
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            int ret = userMapper.resetPassword(user);
            if (ret <= 0) {
                return CommonResult.error();
            }
            return CommonResult.success("重置密码成功！");
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new ServiceException("执行异常");
        }
    }

    @Override
    @Transactional
    public CommonResult deleteUser(String userIds) {
        try {
            if (BaseUtils.isEmpty(userIds)) {
                return CommonResult.error("请检查上送内容");
            }
            String[] Ids = userIds.split(",");
            if (BaseUtils.isEmpty(Ids)) {
                return CommonResult.error("请检查上送内容");
            }
            List<String> userIdList = Arrays.asList(Ids);
            List<User> list = userMapper.selectBatchIds(userIdList);
            if (BaseUtils.isEmpty(list)) {
                return CommonResult.error("请检查上送内容");
            }
            for (User user : list) {
                if (user.getUserId() == 1) {
                    return CommonResult.error("不允许删除admin用户");
                }
                int index = user.getImgPath().lastIndexOf("/");
                String imgName = user.getImgPath().substring(index + 1);
                if (DEFAULT_IMG.equals(imgName)) {
                    continue;
                }
                File file = new File(IMG_PATH + imgName);
                if (!file.delete()) {
                    return CommonResult.error("删除用户图片失败");
                }
            }
            QueryWrapper<RoleUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("user_id", Ids);
            roleUserMapper.delete(queryWrapper);
            int ret = userMapper.deleteBatchIds(userIdList);
            if (ret <= 0) {
                return CommonResult.error("没有符合的用户，删除用户失败");
            }
            return CommonResult.success("删除用户成功！");
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new ServiceException("执行异常");
        }
    }

    @Override
    @Transactional
    public CommonResult updateUser(MultipartFile file, UserVo user) {
        try {
            if (BaseUtils.isNotNull(file)) {
                String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String newName = BaseUtils.getUUID() + ext;
                String path = IMG_PATH + newName;
                File dest = new File(path);
                if (!dest.exists()) {
                    dest.mkdirs();
                }
                try {
                    file.transferTo(dest);
                } catch (IOException e) {
                    logger.error("上传文件失败", e);
                    return CommonResult.error("服务器上传图片文件失败");
                }
                String imgPath = VIRTUAL_PATH + newName;
                user.setImgPath(imgPath);
            }
            // 删除用户角色
            QueryWrapper<RoleUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId());
            roleUserMapper.delete(queryWrapper);
            List<String> roleIds = user.getRoleIds();
            if (BaseUtils.isNotEmpty(roleIds)) {
                roleUserMapper.insertRoleUser(roleIds, user.getUserId());
            }
            user.setLastUpdateTime(new Date());
            int ret = userMapper.updateUser(user);
            if (ret <= 0) {
                return CommonResult.error("更新用户失败");
            }
            return CommonResult.success("更新用户成功！");
        } catch (Exception e) {
            logger.error("执行异常", e);
            throw new ServiceException("执行异常");
        }
    }

    private CommonResult registerInfoCheck(UserVo user) {
        if (BaseUtils.isNull(user)) {
            return CommonResult.error("请输入注册信息！");
        }
        if (BaseUtils.isEmpty(user.getUserAcct()) || BaseUtils.isEmpty(user.getPassword())
                || BaseUtils.isEmpty(user.getUsername()) || BaseUtils.isEmpty(user.getPhone())) {
            return CommonResult.error("请输入用户账户信息！");
        }
        User user1 = userMapper.selectByInfo(user);
        if (BaseUtils.isNotNull(user1)) {
            if (user.getUserAcct().equals(user1.getUserAcct())) {
                return CommonResult.error("当前用户名已存在！");
            }
            if (user.getPhone().equals(user1.getPhone())) {
                return CommonResult.error("当前手机号已被注册！");
            }
        }
        if (user.getUsername().length() > 10) {
            return CommonResult.error("用户昵称长度不超过10位!");
        }
        if (!Pattern.compile(passwordRegex).matcher(user.getPassword()).matches()) {
            return CommonResult.error(passwordRegexDetail);
        }
        if (!Pattern.compile(usernameRegex).matcher(user.getUserAcct()).matches()) {
            return CommonResult.error(usernameRegexDetail);
        }
        return CommonResult.success();
    }
}




